<?php

namespace app\business\controller;

use app\business\model\BusinessInfo;
use app\business\model\BusinessLessen;
use app\business\model\BusinessTableClassify;
use app\business\model\BusinessClassify;
use app\business\model\BusinessMenu;
use app\business\model\BusinessAddress;
use app\business\model\BusinessEnvironment;
use app\business\model\BusinessOrder;
use app\business\model\BusinessFavourable;
use app\business\model\BusinessPrint;
use think\Db;
use think\Session;
use think\Controller;
use think\Cookie;


class Api extends Controller
{



    public function __construct()
    {
        $this->BusinessPrint = model('BusinessPrint');
        $info = BusinessFavourable::where('lessen_status', 1)->select();

        foreach ($info as $k => $v) {
            $time = time();
            if ($time > $info[$k]['time_out']) {
                BusinessFavourable::where('id', $k)->update(['lessen_status' => 0]);
            }
        }
    }

    //获取热门商家
    public function getHotShop()
    {
        $agent_id = $_GET['agent_id'];
        $where['agent_id'] = $agent_id;
        $where['business_trial'] = 2;
        $where['tuijian'] = 1;

        $data = BusinessInfo::where($where)->order(['sort' => 'asc'])->select();

        return json_encode($data);
    }

	//用于审核
    public function canshow()
    {
		$data = array();
		$version = intval($_GET['version']).'.'.intval($_GET['agent_id']);
		$agent_id = intval($_GET['agent_id']);
		$data['a'] = '0';
		if($version === '19.4'){
			$data['a'] = '1';

            $data['b'] = db('menu')->where('business_id',408)->limit(10)->select();
		}
        return json_encode($data);
    }

    public function getDetailData()
    {
        $num = $_GET['data'];       //当前详情的id

        $data['a'] = BusinessInfo::where('business_id', $num)->find();

        $lat1 = $_GET['lat'];

        $lng1 = $_GET['lng'];

        $lat2 = $data['a']['business_lat'];
        $lng2 = $data['a']['business_lng'];
        $distance = round(6378.138 * 2 * asin(sqrt(pow(sin(($lat1 * pi() / 180 - $lat2 * pi() / 180) / 2), 2)
                + cos($lat1 * pi() / 180) * cos($lat2 * pi() / 180) *
                pow(sin(($lng1 * pi() / 180 - $lng2 * pi() / 180) / 2), 2))), 2);

        $data['a']['business_tel'] = strval($data['a']['business_tel']);

        $data['a']['distance'] = $distance;

        $demo = Db::table('business_comment')->where('shop_id',$num)->avg('comment_star');

        switch (floor($demo)) {
            case 1:
                $data['a']['star'] = 'one-star';
                break;
            case 2:
                $data['a']['star'] = 'two-star';
                break;
            case 3:
                $data['a']['star'] = 'three-star';
                break;
            case 4:
                $data['a']['star'] = 'four-star';
                break;
            default:
                $data['a']['star'] = 'five-star';
                break;
    }

        $a = BusinessEnvironment::where('business_id', $num)->select();
        $data['b']['info_img'] = $a;
        //var_dump($data);die;


        return json_encode($data);
    }

    //计算5公里以内的商家
    function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit = 2, $decimal = 2)
    {
        /**
         * 计算两点地理坐标之间的距离
         * @param  Decimal $longitude1 起点经度
         * @param  Decimal $latitude1 起点纬度
         * @param  Decimal $longitude2 终点经度
         * @param  Decimal $latitude2 终点纬度
         * @param  Int $unit 单位 1:米 2:公里
         * @param  Int $decimal 精度 保留小数位数
         * @return Decimal
         */
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI / 180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if ($unit == 2) {
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }

    public function getHotShops()   //获取到了用户的信息。然后重新找到位置
    {
        $lng = $_GET['lng'];        //起点经度

        $lat = $_GET['lat'];        //纬度

        $openId = $_GET['openId'];

        $agent_id = $_GET['agent_id'];

        $demo = Db::table('business_distance')->where('openId', $openId)->find();

        if ($demo) {
            $data = [
                'business_lat' => $lat,
                'business_lng' => $lng
            ];

            Db::table('business_distance')->where('openId', $openId)->update($data);
        } else {
            $data = [
                'openId' => $openId,
                'business_lat' => $lat,
                'business_lng' => $lng
            ];

            Db::table('business_distance')->insert($data);
        }

        $data = Db::query("SELECT *, (select count(1) from business_table as b
                    where a.business_id = b.business_id and table_status=1) as count,round(6378.138*2*asin(sqrt(pow(sin( ($lat*pi()/180-business_lat*pi()/180)/2),2)
                    +cos($lat*pi()/180)*cos(business_lat*pi()/180)*
                    pow(sin( ($lng*pi()/180-business_lng*pi()/180)/2),2))),2)
                    AS juli
                    FROM business_info as a WHERE agent_id = $agent_id AND business_trial = 2 AND business_static = 1
                    ORDER BY juli ASC ,business_goods DESC
                    ");

        return json_encode($data);
    }

    //获取都用户的信息，然后保存在数据库。下次直接调用
    public function getNowShop()
    {
        $num = $_GET['id'];

        $data = Db::query("select *,
        (select count(1) from business_table where table_status=1 )as rest
        from business_info where business_id= $num ");

        $data['0']['business_tel'] = strval($data['0']['business_tel']);

        $data['0']['business_service_price'] = intval($data['0']['business_service_price']);

        $data['0']['business_member_price'] = intval($data['0']['business_member_price']);



        return json_encode($data['0']);
    }

    public function getNowShops()
    {
        $num = $_GET['id'];

        $openId = $_GET['openId'];

        $data = Db::query("select *,
        (select count(1) from business_table where table_status=1 )as rest
        from business_info where business_id= $num ");

        $bool = Db::table('business_order')->where('openId',$openId)->count();

        if($bool>=1){
            $data['0']['business_member_price'] = 0;
        }else{
            $data['0']['business_member_price'] = intval($data['0']['business_member_price']);
        }

        $data['0']['business_tel'] = strval($data['0']['business_tel']);

        $data['0']['business_service_price'] = intval($data['0']['business_service_price']);

        return json_encode($data['0']);
    }

    public function getCarouse()
    {

        $where['fid'] = 1;
        $data = db('carousel')->where($where)->order('sort desc')->select();
        //var_dump($data);die;
        return json_encode($data);
    }

    public function Info()
    {
        $data = db('shop_type')->select();
        $a = array();
        foreach ($data as $key => $value) {
            $a[] = $value['shop_type_name'];
        }

        return json_encode($a);
    }

    public function getshop1()
    {


        $data['business_name'] = input('get.shopName');
        $data['agent_id'] = intval(input('get.agent_id'));
        $data['business_pt'] = date('Y-m-d');
        $data['business_static'] = 1;
        $business_fid = input('get.business_fid');
//var_dump($data['agent_id']);die;
        $s = db('shop_type')->where('shop_type_name', "$business_fid")->find();

        $data['business_fid'] = $s['id'];

        $id = db('info')->insertGetId($data);

        return json_encode($id);


    }

    public function uploads()
    {


        $file = request()->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/shop');
            if ($info) {

                $nowDate = date('Ymd');

                $data = $nowDate . '/' . $info->getFilename();

            } else {
                // 上传失败获取错误信息
                $data = $file->getError();
            }
        } else {
            $data = '失败';
        }


        return json_encode($data);
    }

    public function getshop2()
    {

        $id = input('get.info_id');

        $front = input('get.ceImg');

        $f = str_replace('"', '', $front);

        $a['front'] = str_replace('\\', '', $f);

        $within = input('get.sideImg');

        $w = str_replace('"', '', $within);

        $a['within'] = str_replace('\\', '', $w);

        $data['shop_img_id'] = db('shop_img')->insertGetId($a);
        $data['business_address'] = input('get.address');
        $data['business_lat'] = input('get.business_lat');
        $data['business_lng'] = input('get.business_lng');
        $b['contact_tel'] = input('get.contact_tel');
        $b['contact_user'] = input('get.contact_user');
        //登录信息
        $c['username'] = input('get.username');
        $c['password'] = password_hash(input('password'), PASSWORD_DEFAULT);
        $c['business_id'] = $id;
        db('login')->insertGetId($c);
        $update['business_logo'] = $a['front'];
        $update['id'] = $id;
        db::table('business_info')->update($update);
        $data['contact_id'] = db('contact')->insertGetId($b);
        $model = db('info')->where('id', $id)->update($data);
        db('info')->where('id', $id)->update(['business_id'=>$id]);


        return json_encode($id);
    }

    public function getshop3()
    {


        $info_id = input('get.info_id');

        //获取法人信息
        $a['user'] = input('get.user');
        $a['user_number'] = input('get.user_number');

        $I = input('get.IdceImg');

        $II = str_replace('"', '', $I);

        $a['identity'] = str_replace('\\', '', $II);
        // return json_encode($a['identity']);die;
        $a_id = db('shop_method')->insertGetId($a);

        //执照信息
        $b['license_name'] = input('get.license_name');
        $b['license_number'] = input('get.license_number');
        $b['license_location'] = input('get.license_location');
        $ce = input('get.censeImg');

        $cen = str_replace('"', '', $ce);

        $b['license_img'] = str_replace('\\', '', $cen);
        $b_id = db('shop_license')->insertGetId($b);

        //许可证信息
        $c['licence_name'] = input('get.licence_name');
        $c['licence_number'] = input('get.licence_number');
        $c['licence_location'] = input('get.licence_location');
        $st = input('get.staurantLicenseImg');

        $sta = str_replace('"', '', $st);

        $c['licence_img'] = str_replace('\\', '', $sta);
        $c_id = db('shop_licence')->insertGetId($c);

        $data['business_method_id'] = $a_id;
        $data['business_license_id'] = $b_id;
        $data['business_licence_id'] = $c_id;
        $data['business_button'] = 1;
        $data['business_trial'] = 1;
        $data['agent_id'] = input('agent_id');

        db('info')->where('id', $info_id)->update($data);

    }


    //获取当前商家的所有桌子
    public function getNowTable()
    {
        $num = $_GET['id'];

        $data = BusinessTableClassify::where('business_id', $num)->select();

        $data = json_encode($data);

        return $data;
    }

    //获取当前商家的环境图片
    public function getNowEnvi()
    {
        $num = $_GET['id'];

        $data = BusinessEnvironment::where('business_id', $num)->select();

        return json_encode($data);
    }

    //获取当前商家的所有菜单
    public function getNowMenu()
    {
        $num = $_GET['id'];

//        $obj = BusinessClassify::where('business_id',$num)->select();

        $obj = Db::query("select * from  business_classify as c where business_id = $num and (select count(1) from business_menu where menu_classify = classify_name )>0 and classify_delete != 0");

        return json_encode($obj);
    }

    //获取当前商家的所有商品
    public function getNowGoods()
    {
        $num = $_GET['id'];

        $info = BusinessClassify::where('business_id', $num)->select();

        $data = Db::query("select * from business_menu where business_id=$num ");

        return json_encode($data);

    }

    //获取当前商家的所有的折扣
    public function getNowShopDiscount()
    {
        $num = $_GET['id'];

        $data = Db::table('business_lessen')->where('business_id', $num)->select();

        return json_encode($data);
    }

    //返回订单中的商品数组
    public function getGoodsArray()
    {
        $shop_id = $_GET['shopid'];

        $get_data = json_decode($_GET['data'],true);

		$menu = db('menu')->where('business_id',$shop_id)->select();

 
      	$xia = 0;

 
        foreach ($menu as $key => $value) {


        	if (!empty($get_data[$value['id']])) {
        		$data[$xia] = $value;
        		$data[$xia]['count'] = $get_data[$value['id']];

        		$xia++;
        	}
        }

        return json_encode($data);
    }

    public function order_shop()
    {

        $oid = input('get.oid');



        $ogoods = db('order_goods')->where('oid',$oid)->select();

        //return json_encode($ogoods);die;
        $xia = 0;
        foreach ($ogoods as $key => $value) {
          $shop[$xia] = db('menu')->find($value['gid']);
          $shop[$xia]['count'] = $value['number'];
 return json_encode($shop);die;

            $xia++;
        }


        //var_dump($data);die;

    }

    //获取订单中的商家的商品
    public function getMemberGoods()
    {
        $count = $_GET['data'];


        return $count;
    }

    //获取当前商品的餐盒费
    public function getBoxPrice()
    {
        $shop_id = $_GET['shopid'];

        $get_data = json_decode($_GET['data'],true);
 
        $menu_box_price = 0;
		$menu = db('menu')->where('business_id',$shop_id)->select();

		foreach ($menu as $key => $value) {

			if (!empty($get_data[$value['id']])) {
					$menu_box_price += $value['menu_box_price'];
			}
 
			

		}
        return $menu_box_price;
    }

    //获取当前用户的地址
    public function getMemberAddress()
    {
        $data = $_GET['openId'];

        $info = Db::table('business_address')->where('openId', $data)->select();

        return json_encode($info);
    }

    //改变用户的默认地址
    public function getChangeInfo()
    {
        $data = $_GET['openId'];    //需要更改的用户

        $change = $_GET['change'];      //设为默认地址的id
        $awhere['openId'] = $data;
        $awhere['index'] = 1;

        $address = db::table('business_address')->select($awhere);

        foreach ($address as $key => $value) {
            # code...
            $where['index'] = 0;
            $where['id'] = $value['id'];

            Db::table('business_address')->update($where);
        }

        $info = Db::table('business_address')->where('openId', $data)->update(['index' => 0]);

        $demo = Db::table('business_address')->where('id', $change)->update(['index' => 1]);
    }

    //删除当前用户的地址
    public function deleteAddress()
    {
        $id = $_GET['id'];

        $info = Db::table('business_address')->where('id', $id)->delete();
    }

    //获取当前用户的默认地址
    public function getDefaultAddress()
    {
        $data = $_GET['openId'];    //需要获取的用户

        $info = Db::table('business_address')->where('openId', $data)->where('index', 1)->find();

        return json_encode($info);
    }

    //获取openId
    public function getMemberOpenid()
    {
        $appId = $_GET['appId'];
        $secret = $_GET['secret'];
        $code = $_GET['code'];

        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$secret&js_code=$code&grant_type=authorization_code";
        //return $URL;
        $apiData = file_get_contents($URL);

        //var_dump($apiData);die;
        return $apiData;
    }

    //增加地址
    public function putaddress()
    {
        $data = [
            'name' => $_GET['name'],
            'openId' => $_GET['openId'],
            'tel' => $_GET['phone'],
            'address' => $_GET['city'],
            'detail' => $_GET['cityDetail'],
            'index' => 0,
            'sex' => $_GET['sex'] == '先生' ? 1 : 0,
        ];
        if ($_GET['id']) {
            $id = $_GET['id'];
            $demo = BusinessAddress::where('id', $id)->find();
            if ($demo['index'] == 1) {
                $data['index'] = 1;
            }
            BusinessAddress::where('id', $id)->update($data);
        } else {
            BusinessAddress::create($data);
        }
    }

    //编辑地址
    public function EditMemberAddress()
    {
        $id = $_GET['id'];

        $info = BusinessAddress::where('id', $id)->find();

        return json_encode($info);
    }

    //获取当前商家的所有评论
    public function getComments()
    {
        $id = $_GET['id'];

        $info = Db::table('business_comment')->where('shop_id', $id)->select();

        return json_encode($info);
    }

    public function index_type()
    {

        $openId = $_GET['openId'];


        $lat = input('get.lat');
        $lng = input('get.lon');

        $agent_id = $_GET['agent_id'];
        $fid = input('get.fid');


        $data['a'] = Db::query("SELECT *,floor((select avg(comment_star) from business_comment as c where a.business_id = c.shop_id)) as star, (select count(1) from business_table as b
                    where a.business_id = b.business_id and table_status=1) as count,round(6378.138*2*asin(sqrt(pow(sin( ($lat*pi()/180-business_lat*pi()/180)/2),2)
                    +cos($lat*pi()/180)*cos(business_lat*pi()/180)*
                    pow(sin( ($lng*pi()/180-business_lng*pi()/180)/2),2))),2)
                    AS juli
                    FROM business_info as a  where agent_id = $agent_id AND business_fid = $fid AND business_trial = 2
                    ORDER BY juli ASC ,business_goods DESC
                    ");
        $type = db('shop_type')->find($fid);
        $data['b'] = $type['shop_type_name'];


         foreach($data['a'] as $k=>$v){
                //算出星级
                switch ($v['star']) {
                    case 1:
                        $v['star'] = 'one-star';
                        break;
                    case 2:
                        $v['star'] = 'two-star';
                        break;
                    case 3:
                        $v['star'] = 'three-star';
                        break;
                    case 4:
                        $v['star'] = 'four-star';
                        break;
                    default:
                        $v['star'] = 'five-star';
                        break;
                }
                $data['a'][$k] = $v;
            }

        return json_encode($data);
    }

    //获取用户地址信息
    public function getBeforedistance()
    {
        $openId = $_GET['openId'];

        $info = Db::table('business_distance')->where('openId', $openId)->find();

        if ($info) {
            $lat = $info['business_lat'];       //经纬度

            $lng = $info['business_lng'];
        } else {
            $lat = '30.207351';

            $lng = '120.209929';
        }

        $order = $_GET['order'];

        $agent_id = $_GET['agent_id'];
        $fid = 1;
        switch ($order){
            //推荐列表
            case 'recommend':
                 $data = Db::query("SELECT *
                    ,floor((select avg(comment_star) from business_comment as c
                     where a.business_id = c.shop_id)) as star,
                      (select count(1) from business_table as b
                    where a.business_id = b.business_id and table_status=1) as count,
                    (select CONCAT('满',full,'减',reduce) from business_coupon as d where d.business_id=a.business_id ORDER BY post_time DESC LIMIT 1) as coupon_name,
                    round(6378.138*2*asin(sqrt(pow(sin( ($lat*pi()/180-business_lat*pi()/180)/2),2)
                    +cos($lat*pi()/180)*cos(business_lat*pi()/180)*
                    pow(sin( ($lng*pi()/180-business_lng*pi()/180)/2),2))),2)
                    AS juli
                    FROM business_info as a  where agent_id = $agent_id AND tuijian = 1 AND business_trial = 2
                    ORDER BY juli ASC ,business_goods DESC
                    ");

               // var_dump($data);die;
                break;
                //销量列表
            case 'goods':
                $data = Db::query("SELECT *
                    ,floor((select avg(comment_star) from business_comment as c
                     where a.business_id = c.shop_id)) as star,
                      (select count(1) from business_table as b
                    where a.business_id = b.business_id and table_status=1) as count,
                    (select CONCAT('满',full,'减',reduce) from business_coupon as d where d.business_id=a.business_id ORDER BY post_time DESC LIMIT 1) as coupon_name,
                    round(6378.138*2*asin(sqrt(pow(sin( ($lat*pi()/180-business_lat*pi()/180)/2),2)
                    +cos($lat*pi()/180)*cos(business_lat*pi()/180)*
                    pow(sin( ($lng*pi()/180-business_lng*pi()/180)/2),2))),2)
                    AS juli
                    FROM business_info as a where agent_id = $agent_id AND business_trial = 2
                    ORDER BY juli ASC ,business_goods DESC
                    ");
                break;
            case 'score':
               $data = Db::query("SELECT *
                    ,floor((select avg(comment_star) from business_comment as c
                     where a.business_id = c.shop_id)) as star,
                      (select count(1) from business_table as b
                    where a.business_id = b.business_id and table_status=1) as count,
                    (select CONCAT('满',full,'减',reduce) from business_coupon as d where d.business_id=a.business_id ORDER BY post_time DESC LIMIT 1) as coupon_name,
                    round(6378.138*2*asin(sqrt(pow(sin( ($lat*pi()/180-business_lat*pi()/180)/2),2)
                    +cos($lat*pi()/180)*cos(business_lat*pi()/180)*
                    pow(sin( ($lng*pi()/180-business_lng*pi()/180)/2),2))),2)
                    AS juli
                    FROM business_info as a where agent_id = $agent_id AND business_trial = 2
                    ORDER BY star ASC ,business_goods DESC
                    ");
                break;
            default:
                $data = Db::query("SELECT *
                    ,floor((select avg(comment_star) from business_comment as c
                     where a.business_id = c.shop_id)) as star,
                      (select count(1) from business_table as b
                    where a.business_id = b.business_id and table_status=1) as count,
                    (select CONCAT('满',full,'减',reduce) from business_coupon as d where d.business_id=a.business_id ORDER BY post_time DESC LIMIT 1) as coupon_name,
                    round(6378.138*2*asin(sqrt(pow(sin( ($lat*pi()/180-business_lat*pi()/180)/2),2)
                    +cos($lat*pi()/180)*cos(business_lat*pi()/180)*
                    pow(sin( ($lng*pi()/180-business_lng*pi()/180)/2),2))),2)
                    AS juli
                    FROM business_info as a
                    where agent_id = $agent_id AND business_trial = 2
                    ORDER BY juli ASC ,business_goods DESC
                    ");
                break;
        }

            foreach($data as $k=>$v){
                //算出星级
                switch ($v['star']) {
                    case 1:
                        $v['star'] = 'one-star';
                        break;
                    case 2:
                        $v['star'] = 'two-star';
                        break;
                    case 3:
                        $v['star'] = 'three-star';
                        break;
                    case 4:
                        $v['star'] = 'four-star';
                        break;
                    default:
                        $v['star'] = 'five-star';
                        break;
                }
                $data[$k] = $v;
            }

        return json_encode($data);
    }

//    //获取当前推荐的列表
//    public function getrecommend()
//    {
//        $info = BusinessInfo::order(['id' => 'desc'])->select();
//
//        return json_encode($info);
//    }
//
//    //获取当前销量列表
//    public function getSales()
//    {
//        $info = BusinessInfo::order(['business_goods' => 'desc'])->select();
//
//        return json_encode($info);
//    }
//
//    //获取当前评分列表
//    public function getScore()
//    {
//        $info = BusinessInfo::order(['id' => 'desc'])->select();
//
//        return json_encode($info);
//    }

    //获取上一次的位置
    public function getposition()
    {
        $openId = $_GET['openId'];

        $info = Db::table('business_distance')->where('openId', $openId)->find();

        return json_encode($info);
    }

    //微信支付
    public function Pay()
    {
        //当前用户的agent_id
        $agent_id = $_GET['agent_id'];
        $setting = Db::table('business_setting')->where('agent_id',$agent_id)->find();

        //当前需要充值的openid
        $openId = $_GET['openId'];
        //价格1
        $payMoney = $_GET['total_fee'];
//        $payMoney = 0.01;
        $appid = $setting['appid'];//如果是公众号 就是公众号的appid
        $body = '购买的商品';
        $mch_id = $setting['mch_id'];
        $nonce_str = $this->nonce_str();//随机字符串
        $notify_url = $setting['notify_url'];
        $openid = $openId;
        $out_trade_no = date('Ymd')  . rand(10, 99).rand(10, 99).rand(10, 99).rand(10, 99);//商户订单号
        $spbill_create_ip =$setting['spbill_create_ip'];
        $total_fee = $payMoney * 100;//因为充值金额最小是1 而且单位为分 如果是充值1元所以这里需要*100
        $trade_type = 'JSAPI';//交易类型 默认
        //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错
        $post['appid'] = $appid;
        $post['body'] = $body;
        $post['mch_id'] = $mch_id;
        $post['nonce_str'] = $nonce_str;//随机字符串
        $post['notify_url'] = $notify_url;
        $post['openid'] = $openid;
        $post['out_trade_no'] = $out_trade_no;
        $post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
        $post['total_fee'] = $total_fee;//总金额 最低为一块钱 必须是整数
        $post['trade_type'] = $trade_type;

        $sign = $this->sign($post,$setting['wx_key']);//签名
//var_dump($sign);die;
        $xml = '<xml>
                   <appid>' . $appid . '</appid>
                   <body>' . $body . '</body>
                   <mch_id>' . $mch_id . '</mch_id>
                   <nonce_str>' . $nonce_str . '</nonce_str>
                   <notify_url>' . $notify_url . '</notify_url>
                   <openid>' . $openid . '</openid>
                   <out_trade_no>' . $out_trade_no . '</out_trade_no>
                   <spbill_create_ip>' . $spbill_create_ip . '</spbill_create_ip>
                   <total_fee>' . $total_fee . '</total_fee>
                   <trade_type>' . $trade_type . '</trade_type>
                   <sign>' . $sign . '</sign>
                </xml>';
        //统一接口prepay_id
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $xml = $this->http_request_curl($url, $xml);
        $array = $this->xml($xml);//全要大写
        //halt($array);
        if ($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS') {
            $time = time();
            $tmp = '';//临时数组用于签名
            $tmp['appId'] = $appid;
            $tmp['nonceStr'] = $nonce_str;
            $tmp['package'] = 'prepay_id=' . $array['PREPAY_ID'];
            $tmp['signType'] = 'MD5';
            $tmp['timeStamp'] = "$time";

            $data['state'] = 1;
            $data['timeStamp'] = "$time";//时间戳
            $data['nonceStr'] = $nonce_str;//随机字符串
            $data['signType'] = 'MD5';//签名算法，暂支持 MD5
            $data['package'] = 'prepay_id=' . $array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
            $data['paySign'] = $this->sign($tmp,$setting['wx_key']);//签名,具体签名方案参见微信公众号支付帮助文档;
            $data['out_trade_no'] = $out_trade_no;

        } else {
            $data['state'] = 0;
            $data['text'] = "错误";
            $data['RETURN_CODE'] = $array['RETURN_CODE'];
            $data['RETURN_MSG'] = $array['RETURN_MSG'];
        }
//var_dump($data);die;
        echo json_encode($data);
    }

    function http_request_curl($url, $rawData)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
        curl_setopt($ch, CURLOPT_SSLCERT, dirname(__FILE__).DIRECTORY_SEPARATOR.'apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY, dirname(__FILE__).DIRECTORY_SEPARATOR.'apiclient_key.pem');
        curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).DIRECTORY_SEPARATOR.'rootca.pem');
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: text'
            )
        );
        $data = curl_exec($ch);
        curl_close($ch);
        return ($data);
    }

    //随机32位字符串
    private function nonce_str()
    {
        $result = '';
        $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
        for ($i = 0; $i < 32; $i++) {
            $result .= $str[rand(0, 48)];
        }
        return $result;
    }

    //生成订单号
    private function order_number($openid)
    {
        //date('Ymd',time()).time().rand(10,99);//18位
        return md5($openid . time() . rand(10, 99));//32位
    }

    //签名 $data要先排好顺序
    private function sign($data,$wx_key)
    {
        $stringA = '';
        foreach ($data as $key => $value) {
            if (!$value) continue;
            if ($stringA) $stringA .= '&' . $key . "=" . $value;
            else $stringA = $key . "=" . $value;
        }
        $stringSignTemp = $stringA . '&key=' . $wx_key;//申请支付后有给予一个商户账号和密码，登陆后自己设置key
        return strtoupper(md5($stringSignTemp));
    }

    //curl请求啊
    function http_request($url, $data = null, $headers = array())
    {
        $curl = curl_init();
        if (count($headers) >= 1) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //获取xml
    private function xml($xml)
    {
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals, $index);
        xml_parser_free($p);
        $data = "";
        foreach ($index as $key => $value) {
            if ($key == 'xml' || $key == 'XML') continue;
            $tag = $vals[$value[0]]['tag'];
            $value = $vals[$value[0]]['value'];
            $data[$tag] = $value;
        }
        return $data;
    }

    //获得当前满减活动
    public function getReducePrice()
    {
        $shopId = $_GET['shopId'];      //当前商铺

        $price = $_GET['price'];        //当前价格

        $info = Db::table('business_coupon')->where('business_id', $shopId)->where('full', '<=', $price)->order(['full' => 'desc'])->find();

        $info['reduce'] = intval($info['reduce']);

        return json_encode($info);
    }

    //获得当前所有的优惠券
    public function getAllLessen()
    {
        $agent_id = $_GET['agent_id'];

         $where['l.lessen_date'] = ['>',time()];

        $where['i.agent_id'] = $agent_id;


        $data = Db::table('business_lessen')
                        ->Field('l.id as lid,l.*,i.*')
                        ->alias('l')
                        ->join('info i','l.business_id = i.id' ,'LEFT')
                        ->where($where)
                        ->order('l.id desc')
                        ->select();
        //var_dump($data);die;
        return json_encode($data);
    }
    //获得单个商家优惠券
     public function getshopLessen()
    {
        $shopid = $_GET['shopid'];
        $where['l.lessen_date'] = ['>',time()];

        $where['l.business_id'] = $shopid;

        $data = Db::table('business_lessen')
                        ->Field('l.id as lid,l.*,i.*')
                        ->alias('l')
                        ->join('info i','l.business_id = i.id' ,'LEFT')
                        ->where($where)
                        ->order('l.id desc')
                         ->select();
                          //var_dump($data);die;
        return json_encode($data);
    }

    //获取单一的优惠券
    public function getOneceLessen()
    {
        $id = $_GET['id'];  //需要获取优惠券的id

        $data = BusinessLessen::find($id);

        $data['lessen_date'] = date("Y-m-d ", $data['lessen_date']);

        return json_encode($data);
    }

    //菜单页面优惠券
    public function getOneLessen()
    {
        $id = $_GET['id'];

        $data = BusinessLessen::where('business_id', $id)->order(['lessen_order' => 'desc'])->find();

        if($data){
            $data['lessen_date'] = date("Y-m-d ", $data['lessen_date']);
            return json_encode($data);
        }else{
            $data = [
                'lessen_name' => '暂无优惠券',
                'lessen_full'   => 0,
                'lessen_reduce' => 0,
                'lessen_date'   => '2000-0-0',
                'id'    => 0
            ];
        }


        return json_encode($data);
    }

    //领取优惠券
    public function getFavourableLessen()
    {
        $id = $_GET['id'];          //当前优惠券的id

        $openId = $_GET['openId'];      //当前用户的openId

        $info = BusinessLessen::where('id', $id)->find();

        //首先查看是否有这个优惠券
        $num = BusinessFavourable::where(['shop_id' => $id, 'openId' => $openId])->find();

        if ($num['lessen_count'] == $info['lessen_chance']) {         //每人最多只可以领取一张
            return 1;
        }

        if ($info['lessen_count'] == 0) {
            return 0;
        }

        if ($num) {
            $num['lessen_count'] += 1;

            BusinessFavourable::where(['shop_id' => $id, 'openId' => $openId])->update(['lessen_count' => $num['lessen_count']]);    //增加一张优惠券

            $model = BusinessLessen::where('id', $id)->find();

            $model['lessen_count'] -= 1;

            BusinessLessen::where('id', $id)->update(['lessen_count' => $model['lessen_count']]);
        } else {
            $data = [
                'openId' => $openId,
                'time_out' => $info['lessen_date'],
                'lessen_full' => $info['lessen_full'],
                'lessen_reduce' => $info['lessen_reduce'],
                'shop_id' => $id,
                'lessen_description' => $info['lessen_description'],
                'lessen_status' => 1,
                'shop_name' => $info['lessen_name'],
                'business_id' => $info['business_id']
            ];

            BusinessFavourable::create($data);

            $model = BusinessLessen::where('id', $id)->find();

            $model['lessen_count'] -= 1;

            BusinessLessen::where('id', $id)->update(['lessen_count' => $model['lessen_count']]);
        }
        return 2;
    }

    //获取所有的优惠券
    public function getFavourableData()
    {
        $openId = $_GET['openId'];

        $shopId = $_GET['shopId'];
//var_dump($openId);die;

        if (input('get.youhui') == 1) {
            $info = BusinessFavourable::where('openId', $openId)->select();
        }else{
        $info = BusinessFavourable::where('openId', $openId)->where('business_id',$shopId)->select();
        }
        foreach ($info as $k => $v) {
            $info[$k]['time_out'] = date("Y-m-d ", $info[$k]['time_out']);
        }
       // var_dump($info);die;
        return json_encode($info);
    }

    public function putOrder()
    {



        //订单内商品
        $shangpin= input('get.shangpin');
         
        $shangpin= str_replace('[','',$shangpin);
        $shangpin= str_replace(']','',$shangpin);
        $shangpin= explode(',',$shangpin);
        //订单内商品数
        $shangpinshu = input('get.shangpinshu');
        $shangpinshu = str_replace('[','',$shangpinshu);
        $shangpinshu = str_replace(']','',$shangpinshu);
        $shangpinshu = explode(',',$shangpinshu);

        //return json_encode($zifu);die;
        $xia = 0;
        foreach ($shangpin as $key => $value) {
            //return $value;die;
            $ogoods[$xia] = db('menu')->find($value);
            $zifu = $shangpinshu[$xia];
            $zifu = rtrim($zifu,'""');
            $zifu = ltrim($zifu,'""');
            //return json_encode($ogoods[$xia]);die;
            $ogoods[$xia]['number'] = $zifu;

            $xia++;
        }



//return json_encode($ogoods);die;


        $openId = $_GET['openId'];  //客户的openId
        $shopId = $_GET['shopId'];  //购买的是哪个商家
        $order = $_GET['order'];    //购买的订单
        $address = $_GET['address'];    //购买的地址

        $allPrice = $_GET['allPrice'];  //购买的总价格
        $lessen_id = $_GET['lessen_id'];    //购买的优惠券的id
        $remarks = $_GET['remarks'];    //购买商品时发布的备注
        $status = $_GET['status'];      //当前订单的状态

        //return json_encode($status);die;
        $reducePrice = $_GET['reducePrice'];     //优惠的总金额
        $allPayMoney = $_GET['allPayMoney'];        //应该支付的总价格
        $access = $_GET['access_token'];        //当前的access_token
        $packages = $_GET['packages'];      //当前的form_id
        $demo = $shangpin;
        //当前时间
        $dqtime = time();
         //平台订单号
        $ptdingdan = date('Ymd')  . rand(10, 99).rand(10, 99).rand(10, 99);
        $info = BusinessInfo::where('business_id', $shopId)->find();

          $add = Db::table('business_address')->where('id', $address)->find();








//  $data = array(
//         'shop_no'=>  '6005',//门店编号
//         'origin_id'=> '564548873',//订单id
//         'city_code'=> '021',//城市
//         'tips'=> 0,//小费
//         'cargo_price'=> 0.1,
//         // 'cargo_num'=> 2,
//         'is_prepay'=> 0,
//         'expected_fetch_time'=>time()+600,
//         'receiver_name'=> '杨天宇',
//         'receiver_address'=> '聚光中心bbb',
//         'receiver_lat'=> '30.2084',
//         'receiver_lng'=> '120.21201',
//         'receiver_phone'=> '17342052373',
//         'callback'=>'https://www.baidu.com/'
//         //'callback'=>'http://newopen.imdada.cn/inner/api/order/status/notify'
//     );
//         $data['city_code'] = $this->shujv();
// //var_dump($data);die;
//         $data = json_encode($data);

//         $requestParams = array();
//         $requestParams['app_key'] = $this->app_key;
//         $requestParams['body'] = $data;
//         $requestParams['format'] = 'json';
//         $requestParams['v'] = '1.0';
//         $requestParams['source_id'] = '73753';
//         $requestParams['timestamp'] = time();

//         $requestParams['signature'] = $this->paixu($requestParams);
//  //var_dump($requestParams['signature']);die;
//         $data = $this->post($requestParams,$this->addorderurl);
































        $shop_data = [];    //这个是商品的信息
        foreach ($demo as $k=>$v){
            if($v!=''){
                $shop_data[$k]=$v;
            }
        }

             //return input('get.openId');die;





//        foreach (json_decode($shopData) as $k=>$v) {
//            return $v.$k;
//        }
        if ($_GET['again'] !== "undefined" && $status == '1') {     //如果这个是未提交一次的订单
            BusinessOrder::where('id', $_GET['again'])
                ->update([
                    'order_status' => 1,
                    'lessen_id' => $lessen_id,
                    'reducePrice' => $reducePrice,
                    'allPayMoney' => $allPayMoney,
                    'order_pay' => $allPrice
                ]);
                        $member = BusinessOrder::where('id',$_GET['again'])->find();
                        $models = Db::table('business_cash')->where('business_id',$member['shop_id'])->find();
                        if($models!=$member['shop_id']){
                            $num = $models['cash_num']+$allPrice;
                            Db::table('business_cash')->where('business_id',$member['shop_id'])->update(['cash_num'=>$num]);
                        }else{
                            $data = [
                              'business_id' => $member['shop_id'],
                              'cash_num'    => $allPrice
                            ];
                            Db::table('business_cash')->insert($data);
                        }
            return 'ok';
        }

        if ($_GET['again'] !== "undefined" && $status == 2) {
            return 'error';
        }



        if ($lessen_id != 0 && $status == '1') {
            $test = BusinessFavourable::where('id', $lessen_id)->setInc('lessen_use');

            $model = BusinessFavourable::where('id', $lessen_id)->find();
            if ($model['lessen_use'] == $model['lessen_count']) {
                BusinessFavourable::where('id', $lessen_id)->update(['lessen_status' => 2]);
            }
        }


        //return  json_encode($shopData);die;
        $order_static = input('get.order_static');


        $zhifustatic = input('get.zhifustatic');
        //return $zhifustatic;die;
        if ($zhifustatic == 1) {
            # code...

         //查找属于当前商家的打印机
        $printerwhere = array(
            'printer_status' => 1,
            'printer_shop_id' => $shopId
            );


        $dayin = db('printer')->where($printerwhere)->select();

        if ($order_static == 1) {
           //店内点餐

            foreach ($dayin as $key => $value) {

                    $contents ='<FS>店内就餐单</FS>\r\n\r\n';
                    $contents .='<FS>单号：'.$ptdingdan.' </FS>\r\n';
                    $contents .='<FS>'.$info['business_name'].'</FS>\r\n\r\n';
                    $contents .='打单时间：'.date('Y-m-d H:i:s').' \r\n';
                    $contents .='支付方式：微信支付\r\n';
                    $contents .='<table><tr><td>--------------------------------</td></tr></table>';//32个字符
                    $contents .='<table>';
                    $contents .='<tr><td>商品</td><td>数量</td><td>小计</td></tr>';
                    foreach ($ogoods as $key => $v) {
                        $contents .= '<tr><td>'.$v['menu_name'];

                        $contents .= '</td><td>'.$v['number'].'</td><td>'.$v['menu_shop_price']*$v['number'].'</td></tr>';
                    }
                    $contents .='</table>';
                    $contents .='<table><tr><td>--------------------------------</td></tr></table>';//32个字符
                    $contents .='优惠:-'.input('get.reducePrice').'元'.'\r\n';
                    $contents .='<FS>合计：￥'.input('get.allPayMoney').'元'.'</FS>\r\n';
                    $contents .='备注：'.input('get.remarks').'\r\n\r\n';

                        $this->BusinessPrint->action_print($value['printer_uid'],$value['printer_code'],$contents,$value['printer_api'],$value['printer_dayiji']);


                }

        }else if($order_static == 2){
           //外卖点餐


               foreach ($dayin as $key => $value) {

                    $contents ='<FS>外卖订餐</FS>\r\n\r\n';
                    $contents .='<FS>单号：'.$ptdingdan.' </FS>\r\n';
                    $contents .='<FS>'.$info['business_name'].'</FS>\r\n\r\n';
                    $contents .='<FS>'.$add['address'].$add['detail'].$add['tel'].'</FS>\r\n\r\n';
                    $contents .='打单时间：'.date('Y-m-d H:i:s').' \r\n';
                    $contents .='支付方式：微信支付\r\n';
                    $contents .='<table><tr><td>--------------------------------</td></tr></table>';//32个字符
                    $contents .='<table>';
                    $contents .='<tr><td>商品</td><td>数量</td><td>小计</td></tr>';
                    foreach ($ogoods as $key => $v) {
                        $contents .= '<tr><td>'.$v['menu_name'];

                        $contents .= '</td><td>'.$v['number'].'</td><td>'.$v['menu_shop_price']*$v['number'].'</td></tr>';
                    }
                    $contents .='</table>';
                    $contents .='<table><tr><td>--------------------------------</td></tr></table>';//32个字符
                    $contents .='优惠:-'.input('get.reducePrice').'\r\n';
                    $contents .='<FS>合计：￥'.input('get.allPayMoney').'</FS>\r\n';
                    $contents .='备注：'.input('get.remarks').'\r\n\r\n';

                        $this->BusinessPrint->action_print($value['printer_uid'],$value['printer_code'],$contents,$value['printer_api'],$value['printer_dayiji']);
                }





        }

}

        $agent = db('setting')->where('agent_id',input('get.agent_id'))->find();

 if ($status == 1) {
            //修改语音播报表
            $txupdate['id'] = 1;
            $txupdate['value'] = 1;
            db('tixing')->update($txupdate);
            //发送短信
             if ($info['duanxin'] == 1) {
               //开启短信通知  开始发送

                $res = sendSms($info['dxphone'],rand(100000,999999),$info['dxsginName'],$info['dxTemplateCode'],$info['dxaccessKeyId'],$info['dxaccessKeySecret']);
             }
               //发送邮件
             if ($info['email'] == 1) {
                 # code...
                 # 开启邮件通知   开始发送

                $setting = db('setting')->find($info['agent_id']);

            //引入核心文件
            require './vendor/PHPMailer-5.2.7/class.phpmailer.php';

            $mail = new \PHPMailer();


             //是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
            $mail->SMTPDebug = 1;

            //使用smtp鉴权方式发送邮件，当然你可以选择pop方式 sendmail方式等 本文不做详解
            //可以参考https://phpmailer.github.io/PHPMailer/当中的详细介绍
            $mail->isSMTP();
            //smtp需要鉴权 这个必须是true
            $mail->SMTPAuth=true;
            //链接qq域名邮箱的服务器地址
            $mail->Host = 'smtp.qq.com';
            //设置使用ssl加密方式登录鉴权
            $mail->SMTPSecure = 'ssl';
            //设置ssl连接smtp服务器的远程服务器端口号 可选465或587
            $mail->Port = 465;
            //设置smtp的helo消息头 这个可有可无 内容任意
            $mail->Helo = '';
            //设置发件人的主机域 可有可无 默认为localhost 内容任意，建议使用你的域名
            $mail->Hostname = 'app.yizhizaibo.cn';
            //设置发送的邮件的编码 可选GB2312 我喜欢utf-8 据说utf8在某些客户端收信下会乱码
            $mail->CharSet = 'UTF-8';
            //设置发件人姓名（昵称） 任意内容，显示在收件人邮件的发件人邮箱地址前的发件人姓名
            $mail->FromName = $setting['email_name'];
            //smtp登录的账号 这里填入字符串格式的qq号即可
            $mail->Username = $setting['email_qq'];
            //smtp登录的密码 这里填入“独立密码” 若为设置“独立密码”则填入登录qq的密码 建议设置“独立密码”
            $mail->Password = $setting['email_pwd'];
            //设置发件人邮箱地址 这里填入上述提到的“发件人邮箱”
            $mail->From = $setting['email_yx'];
            //邮件正文是否为html编码 注意此处是一个方法 不再是属性 true或false
            $mail->isHTML(true);
            //设置收件人邮箱地址 该方法有两个参数 第一个参数为收件人邮箱地址 第二参数为给该地址设置的昵称 不同的邮箱系统会自动进行处理变动 这里第二个参数的意义不大
            //添加多个收件人 则多次调用方法即可
            $mail->addAddress($info['email_dz'],'');
            
            //添加该邮件的主题
            $mail->Subject = $setting['email_theme'];
            //添加邮件正文 上方将isHTML设置成了true，则可以是完整的html字符串 如：使用file_get_contents函数读取本地的html文件
            $mail->Body = "您的商城有一份<b style=\"color:red;\">新订单</b>！请尽快处理哦！";
            //为该邮件添加附件 该方法也有两个参数 第一个参数为附件存放的目录（相对目录、或绝对目录均可） 第二参数为在邮件附件中该附件的名称
            ////同样该方法可以多次调用 上传多个附件
            // $mail->addAttachment('./d.jpg','mm.jpg');



            //发送命令 返回布尔值
            //PS：经过测试，要是收件人不存在，若不出现错误依然返回true 也就是说在发送之前 自己需要些方法实现检测该邮箱是否真实有效
             $mail->send();



             }
            //已支付
            $type = 3;
            $content['time'] = date('Y-m-d H:i:s');
            $content['danhao'] = $ptdingdan;
            $xia = 1;

            foreach ($ogoods as $key => $value) {

                $shopname[$xia] = $value['menu_name'];

              $xia++;
            }

            $content['shopname'] = implode(',',$shopname);
            $content['money'] = $allPayMoney;

             $content['blade_id'] = $agent['blade_id'];
        }elseif($status ==2){

            //var_dump(222);die;
            $type = 4;

            $content['xiadantime'] = date('Y年m月d日 H时i分s秒');
            $content['zhifutime'] = date('Y-m-d H:i:s');
             $content['gmsb_id'] = $agent['gmsb_id'];

        }
        $content['openid'] = $openId;
        $content['form_id'] = $packages;


        $content['appid'] = $agent['appid'];
        $content['appsecret'] = $agent['appsecret'];
       //var_dump($type);die;
        $a = send_notice_pay($content,$type);
        //return json_encode($a);
//var_dump($a);die;
        $data = [
            'shop_id' => $shopId,   //商家信息

            'user_lat' => input('get.lat'),
            'user_lng' => input('get.lng'),
            'order_num' => input('get.order'), //平台订单号
            'wechat_order' => $order,    //腾讯订单号
            'order_name' => $add['name'],
            'order_address' => $add['address'].$add['detail'],
            'static' => $order_static,
            'order_tel' => $add['tel'],
            'order_pay' => $allPrice,
            'order_time' => $dqtime,
            'openId' => $openId,
            'lessen_id' => $lessen_id,
            'order_remark' => $remarks,
            'order_status' => $status,
            'order_img' => $info['business_logo'],
            'reducePrice' => $reducePrice,
            'allPayMoney' => $allPayMoney,
            'table_id' => input('get.table_id'),
            'tknum' => $this->nonce_str().$this->nonce_str(),
        ];

        $chang_num = $data['order_num'];


        //添加插入到订单表
        //$orderid = BusinessOrder::insertGetId($data);
        $orderid = db::table('business_order')->insertGetId($data);
        //return json_encode($ogoods);die;
         foreach ($ogoods as $key => $value) {

             $order_goods['goods_name'] = $value['menu_name'];

             $order_goods['goods_side_price'] = $value['menu_side_price'];
             $order_goods['number'] = $value['number'];
             $order_goods['gid'] = $value['id'];
             $order_goods['business_id'] = $value['business_id'];
             $order_goods['oid'] = $orderid;
             $order_goods['picture_url'] = $value['menu_img'];
             $order_goods['goods_box_price'] = $value['menu_box_price'];

             db('order_goods')->insert($order_goods);

         }
        if($status==1){
            $infos = Db::table('business_cash')->where('business_id',$shopId)->find();
            if($infos){
                $cash = $infos['cash_num']+$allPrice;
                Db::table('business_cash')->where('business_id',$shopId)->update(['cash_num'=>$cash]);
            }else{
                $dataes = [
                    'business_id' => $shopId,
                    'cash_num'    => $allPrice
                ];
                Db::table('business_cash')->insert($dataes);
            }
        }
//        $packages = substr($packages, 10, 50);
        //发送模板消息    用户
        // $data = explode(",", $shopData);

        // $model = [];

        // $demo = BusinessMenu::all();

        // foreach ($data as $k => $v) {
        //     if ($data[$k] !== '') {
        //         $demo[$k - 1]->count = $data[$k];
        //         array_push($model, $demo[$k - 1]);
        //     }
        // }

        // $goods= '';
        // foreach ($model as $k=>$v){
        //     $goods = $goods.$model[$k]['menu_name'].'X'.$model[$k]['count'];
        // }

        // $order_date = date("Y-m-d H:i:s",time());
        // //给用户的
        // $data_arr = array(
        //     'keyword1' => array( "value" => $info['business_name'], "color" => '#173177' ),
        //     'keyword2' => array("value" =>  $goods , "color" => '#173177'),
        //     'keyword3' => array("value" => '一份',"color" => '#173177'),
        //     'keyword4' => array("value"=> $chang_num,"color" => '#173177'),
        //     'keyword5' => array("value" => "微信支付","color" => '#173177'),
        //     'keyword6' => array("value" => $order_date,"color" => '#173177'),
        //     'keyword7' => array("value" => $order_date,"color" => '#173177'),
        //     'keyword8' => array("value" => $remarks,"color" => '#173177'),
        //     'keyword9' => array("value" => $allPrice,"color" => '#173177'),
        //     //这里根据你的模板对应的关键字建立数组，color 属性是可选项目，用来改变对应字段的颜色
        // );
        //给商家的
//        $data_arr = array(
//            'keyword1' => array( "value" => $goods, "color" => '#173177' ),
//            'keyword2' => array("value" =>  $order_date , "color" => '#173177'),
//            'keyword3' => array("value" => $allPrice,"color" => '#173177'),
//            'keyword4' => array("value"=> $chang_num,"color" => '#173177'),
//            'keyword5' => array("value" => "$address","color" => '#173177'),
//            'keyword6' => array("value" => '外卖',"color" => '#173177'),
//            'keyword7' => array("value" => $info['business_tel'],"color" => '#173177'),
//            'keyword8' => array("value" => $remarks,"color" => '#173177'),
//            'keyword9' => array("value" => '微信支付',"color" => '#173177'),
//            //这里根据你的模板对应的关键字建立数组，color 属性是可选项目，用来改变对应字段的颜色
//        );
        //商家的
        $info_id = $info['agent_id'];
        $appId = Db::table('business_setting')->where('agent_id',$info_id)->find();
        //
        $shop_data = array (
            "touser"           => $openId,
            //用户的 openID，可用过 wx.getUserInfo 获取
            "template_id"      => $appId['appid'],
            //小程序后台申请到的模板编号
//            "page"             => ,
            //点击模板消息后跳转到的页面，可以传递参数
            "form_id"          => $packages,
            //第一步里获取到的 formID
           // "data"             => $data_arr,
            "emphasis_keyword" => "keyword1.DATA"
            //需要强调的关键字，会加大居中显示
        );
        //用户的
//        $post_data = array (
//            "touser"           => $openId,
//            //用户的 openID，可用过 wx.getUserInfo 获取
//            "template_id"      => 'qqFOsX9WHwLJDrUYDn-DkrU2Yb3sX6_AA20IQ4MkzH4',
//            //小程序后台申请到的模板编号
////            "page"             => ,
//            //点击模板消息后跳转到的页面，可以传递参数
//            "form_id"          => $packages,
//            //第一步里获取到的 formID
//            "data"             => $data_arr,
//            "emphasis_keyword" => "keyword1.DATA"
//            //需要强调的关键字，会加大居中显示
//        );

        function send_post( $url, $post_data ) {
            $options = array(
                'http' => array(
                    'method'  => 'POST',
                    'header'  => 'Content-type:application/json',
                    //header 需要设置为 JSON
                    'content' => $post_data,
                    'timeout' => 60
                    //超时时间
                )
            );
            $context = stream_context_create( $options );
            $result = file_get_contents( $url, false, $context );

            return $result;
        }
        //调用发放优惠券


        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access";

//        $data = json_encode($post_data, true);
        $data_shop = json_encode($shop_data, true);
        //将数组编码为 JSON

//        $return = send_post( $url, $data);
        $return_shop = send_post( $url, $data_shop);

        $give = $this->giveLesson($openId,$info_id);
        return json_encode($give);
//        return json_encode($return_shop); 后续的
    }

    //发放优惠券
    private function giveLesson($openId,$info_id)
    {
        $settings = Db::table('business_setting')->where('agent_id',$info_id)->find();
        //xml
        $appid=$settings['appid'];
        $coupon_stock_id = $settings['coupon_stock_id'];
        $mch_id = $settings['mch_id'];
        $nonce_str = $this->nonce_str();
        $openid = $openId;
        $openid_count = 1;
        $partner_trade_no = $this->order_number($openid);
        $post['appid']=$appid;
        $post['coupon_stock_id']=$coupon_stock_id;
        $post['mch_id']=$mch_id;
        $post['nonce_str']=$nonce_str;
        $post['openid']=$openid;
        $post['openid_count']=$openid_count;
        $post['partner_trade_no']=$partner_trade_no;
        $sign = $this->sign($post,$settings['wx_key']);
//        $stringA="appid=wx94470919fbf5ec92&coupon_stock_id=4756512&mch_id=1490668762&
//        nonce_str=$nonce_str&openid=$openid&openid_count=$openid_count&partner_trade_no=$partner_trade_no";
//        $stringSignTemp=$stringA+"&key=619d9e0657a258c24cd1dec2a4b5e544";
//        $sign=strtoupper(MD5($stringSignTemp));
        $xml = '<xml>
                   <appid>' . $appid . '</appid>
                   <coupon_stock_id>' . $coupon_stock_id . '</coupon_stock_id>
                   <mch_id>' . $mch_id . '</mch_id>
                   <nonce_str>' . $nonce_str . '</nonce_str>
                   <openid>' . $openid . '</openid>
                   <openid_count>' . $openid_count . '</openid_count>
                   <partner_trade_no>' . $partner_trade_no . '</partner_trade_no>
                   <sign>' . $sign . '</sign>
                </xml>';
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/send_coupon';
        $xml = $this->http_request_curl($url, $xml);
        $array = $this->xml($xml);//全要大写
        return $array;
    }



    //调用证书
    function curl_post_ssl($url, $vars, $second=30,$aHeader=array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        //curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert.pem');
        //默认格式为PEM，可以注释
        //curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        //curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/private.pem');

        //第二种方式，两个文件合成一个.pem文件
//        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        curl_setopt($ch, CURLOPT_SSLCERT, dirname(__FILE__).DIRECTORY_SEPARATOR.'apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY, dirname(__FILE__).DIRECTORY_SEPARATOR.'apiclient_key.pem');
        curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__).DIRECTORY_SEPARATOR.'rootca.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }



    //获取当前用户未支付订单
    public function getNoOrder()
    {
        $openId = $_GET['openId'];      //当前用户的openId
        //return json_encode($openId);die;
        $data = BusinessOrder::where('openId', $openId)->where('order_status', 2)->order('id desc')->select();

        foreach ($data as $k => $v) {
            $v['order_time'] = date("Y-m-d H:i:s", $v['order_time']);
        }

        return json_encode($data);
    }

    //获取已经支付的订单
    public function getPayOrder()
    {
        $openId = $_GET['openId'];      //当前用户的openId

        $data = BusinessOrder::where('openId', $openId)->where('order_status', 1)->order('id desc')->select();

        foreach ($data as $k => $v) {
            $v['order_time'] = date("Y-m-d H:i:s", $v['order_time']);
        }

        return json_encode($data);
    }

    //小程序上传图片
    public function uploadFile()
    {
        $file = request()->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/shop');
            if ($info) {

                $nowDate = date('Ymd');

                $data = $nowDate . '/' . $info->getFilename();

            } else {
                // 上传失败获取错误信息
                $data = $file->getError();
            }
        } else {
            $data = '失败';
        }


        return $data;
    }

    //上传评论内容
    public function pushMyComment()
    {
        $checkStatus = $_GET['checkStatus'];        //是否匿名提交
        $image = $_GET['image'];    //上传的评论商品图片
        $orderId = $_GET['orderId'];    //当前的订单号
        $content = $_GET['content'];    //当前评论的内容
        $star = $_GET['star'];  //当前评论的星级
        $allPay = $_GET['allPay'];      //人均的价格
        $post_time = time();        //评论的时间
        $openId = $_GET['openId'];      //当前用户的openId
        $person_head = $_GET['person_head'];    //当前评论的用户头像
        $person_name = $_GET['person_name'];        //当前评论的用户名称


        BusinessOrder::where('id', $orderId)->update(['is_comment' => 1]);     //更改订单的状态

        switch ($star) {
            case 0:
                $star_data = 'one-star';
                break;
            case 1:
                $star_data = 'two-star';
                break;
            case 2:
                $star_data = 'three-star';
                break;
            case 3:
                $star_data = 'four-star';
                break;
            default:
                $star_data = 'five-star';
                break;
        }

        $shop_id = BusinessOrder::where('id', $orderId)->find();

        $data = [
            'mark' => $star_data,
            'comment' => $content,
            'post_time' => $post_time,
            'comment_image' => $image,
            'person_price' => $allPay,
            'check_status' => $checkStatus,
            'openId' => $openId,
            'shop_id' => $shop_id['shop_id'],
            'person_head' => $person_head,
            'person_name' => $person_name,
            'order_id' => $orderId,
            'comment_star' => ($star + 1)
        ];

        Db::table('business_comment')->insert($data);
    }

    //获取到当前商家的平均
    public function getAvgStar()
    {
        $id = $_GET['id'];      //当前平均值

        $star = Db::table('business_comment')->where('shop_id', $id)->avg('comment_star');

        return $star;       //当前的平均值
    }

    //获取平均星级
    public function getAvgStars()
    {
        $star = $_GET['star'];

        switch (floor($star)) {
            case 1:
                $star_data = 'one-star';
                break;
            case 2:
                $star_data = 'two-star';
                break;
            case 3:
                $star_data = 'three-star';
                break;
            case 4:
                $star_data = 'four-star';
                break;
            default:
                $star_data = 'five-star';
                break;
        }

        return $star_data;
    }

    //获取到所有的商品评论
    public function getAllComment()
    {
        $id = $_GET['id'];      //当前的商家id

        $info = Db::table('business_comment')->where('shop_id', $id)->select();

        foreach ($info as $k => $v) {
            $info[$k]['post_time'] = date("Y-m-d ", $info[$k]['post_time']);
        }

        return json_encode($info);
    }

    //获取所有的商品
    public function getAllShops()
    {
        $data = BusinessMenu::all();

        return json_encode($data);
    }

    //获取到搜索的店铺
    public function getSearchShop()
    {
        $desc = $_GET['desc'];

        $agent_id = $_GET['agent_id'];

        $data = Db::query("select *,(SELECT avg(comment_star) FROM business_comment  as c
where c.shop_id=i.business_id ) as star,(select count(1) from business_table as t where table_status= 1 AND i.business_id=t.business_id )as rest from business_info as i where CONCAT(IFNULL(`business_name`,''),IFNULL(`business_circle`,''))  like '%".$desc."%' and agent_id = $agent_id ");


        foreach($data as $k=>$v){
            switch (floor($v['star'])) {
                case 1:
                    $v['star'] = 'one-star';
                    break;
                case 2:
                    $v['star'] = 'two-star';
                    break;
                case 3:
                    $v['star'] = 'three-star';
                    break;
                case 4:
                    $v['star'] = 'four-star';
                    break;
                default:
                    $v['star'] = 'five-star';
                    break;
            }
            $data[$k] = $v;
        }

        return json_encode($data);
    }

    //访问当前扫码的接口
    public function getCodeUrl()
    {
        $data = $_GET['url'];

        $info = file_get_contents($data);

        return $info;
    }

    //获取微信小程序当前的下拉框选择
    public function getSelected()
    {
        $id = $_GET['id'];

        $info = BusinessTableClassify::where('business_id',$id)->select();

        $data=[];

        foreach ($info as $k=>$v){
            array_push($data,$info[$k]['classify_name']);
        }

        return json_encode($data);
    }

    //获取当前商家的基本信息
    public function getTableShop()
    {
        $Id = $_GET['shopId'];

        $data = BusinessInfo::where('business_id',$Id)->find();

        $data['business_tel'] = strval($data['business_tel']);

        return json_encode($data);
    }

    //获取到当前用户预约的信息
    public function pushPersonSubscribe()
    {
        $shopId = $_GET['shopId'];
        $person_name = $_GET['person_name'];
        $person_tel = $_GET['person_tel'];
        $openId = $_GET['openId'];
        $person_mark = $_GET['person_mark'];
        $date = $_GET['date'];
        $time = $_GET['time'];
        $table = $_GET['tablclassify'];
        //获取当前商家的数据
        $info = BusinessInfo::where('business_id',$shopId)->find();

        $data = [
            'shop_logo' => $info['business_logo'],
            'shop_table'    => $table,
            'openId'        => $openId,
            'shop_name'     => $info['business_name'],
            'date'      => $date,
            'time'      => $time,
            'person_name'       => $person_name,
            'person_tel'        => $person_tel,
            'person_mark'       => $person_mark,
            'shop_id'       => $shopId
        ];

        Db::table('business_subscribe')->insert($data);     //加入数据，是预约的信息
    }

    //获取到当前用户的订座信息
    public function getPersonSubscribe()
    {
        $openId = $_GET['openId'];      //当前用户的openId

        $data = Db::table('business_yuyue')->where('openId',$openId)->select(); //获取当前用户的订座信息

       // $model = Db::table('business_distance')->where('openId',$openId)->find();   //获取当前用户的经纬度

        $lat1 = input('get.lat');

        $lng1 = input('get.lng');
        $xia = 0;

        foreach ($data as $k=>$v){

            //var_dump($v);die;
            //获取到平均价格
            $data[$xia]['avg'] = Db::table('business_order')->where('shop_id',$v['shopid'])->avg('order_pay');
             //获取到当前距离
            $info = BusinessInfo::where('business_id', $v['shopid'])->find();
            $lat2 = $info['business_lat'];
            $lng2 = $info['business_lng'];
            $distance = round(6378.138 * 2 * asin(sqrt(pow(sin(($lat1 * pi() / 180 - $lat2 * pi() / 180) / 2), 2)
                    + cos($lat1 * pi() / 180) * cos($lat2 * pi() / 180) *
                    pow(sin(($lng1 * pi() / 180 - $lng2 * pi() / 180) / 2), 2))), 2);

            $data[$xia]['distance'] = $distance;
            //获取到当前商家是否在排队
            $wait = Db::table('business_table')->where('business_id',$v['shopid'])->where('table_status',1)->count();

            $data[$xia]['wait']=$wait;
            $xia++;
        }

        return json_encode($data);
    }

    //删除订单信息
    public function delete_yuyue()
    {
    	$id = input('get.id');

    	$static = db('yuyue')->delete($id);

    	return $static;
    }
    //获取access_token
    public function getAccessToken()
    {
        $appId = $_GET['appId'];

        $secret = $_GET['secret'];

        $data = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$secret");

        return $data;
    }

    //推送模板消息更换openId
    public function pushOpenId()
    {
        $openId= $_GET['openId'];       //用户的openId

        $shopId = $_GET['shopId'];      //用户需要绑定的商家

        BusinessInfo::where('business_id',$shopId)->update(['business_push'=>$openId]);
    }

    //发放代金券
//    public function pushMyLesson()
//    {
//        $access_token = $_GET['access_token'];
//
//
//
//        $data = array(
//            'info' => [
//                "basic_info"=>[
//                    "activity_bg_color" => "Color010",
//                    "activity_tinyappid" => "wx94470919fbf5ec92",
//                    "begin_time" => "1517543342",
//                    "end_time"  =>  "1517583600",
//                    "gift_num"  => "5",
//                    "max_partic_times_act" => "1",
//                    "max_partic_times_one_day" => "1",
//                    "mch_code"  => "1490668762",
//                ],
//                "card_info_list"=>[
//                    "card_id" => "pX2-vjjP47Q9jWbtWZab7Bk9PwKA",
//                    "min_amt" => "100",
//                    "membership_appid" => "wx94470919fbf5ec92",
//                ],
//                [
//                    "custom_info" => [
//                        "type" => "AFTER_PAY_PACKAGE"
//                    ]
//                ]
//            ]
//        );
//        function send_post( $url, $post_data ) {
//            $options = array(
//                'http' => array(
//                    'method'  => 'POST',
//                    'header'  => 'Content-type:application/json',
//                    //header 需要设置为 JSON
//                    'content' => $post_data,
//                    'timeout' => 60
//                    //超时时间
//                )
//            );
//            $context = stream_context_create( $options );
//            $result = file_get_contents( $url, false, $context );
//
//            return $result;
//        }
//        //请求接口
//        $url = "https://api.weixin.qq.com/card/mkt/activity/create?access_token=$access_token";
//
//        $data_lesson= json_encode($data, true);
//        //将数组编码为 JSON
//
//        $return_shop = send_post( $url, $data_lesson);
//
//        return $return_shop;
//    }
    public function getMyAddress()
    {
        $latitude = $_GET['latitude'];

        $longitude = $_GET['longitude'];

        $data = file_get_contents("http://api.map.baidu.com/geocoder/v2/?location=$latitude,$longitude&output=json&pois=1&ak=ox3rlNd0GLgzx8cCesUtxSQW7NcS7GnI");

        return json_encode($data);
    }

    public function type()
    {


        $data = db::table('business_shop_type')->where('static',1)->whereor('caidan',1)->order('sort')->select();
        //var_dump($data);die;
        $xia = 0;
        $daxia = 0;
        foreach ($data as $key => $value) {
            if (!$xia == 0) {
                if ($xia%8 == 0) {
                $daxia++;
            }
            }
            $type[$daxia][$xia] = $value;
            $xia++;
        }

        //var_dump($type);die;
        return json_encode($type);
    }


    public function quhao()
    {
 $data = input('get.');
       // return json_encode(input('get.openid'));die;
        //return json_encode(input('get.'));die;
        $info = db('info')->find(input('get.shopid'));

        $data['shop_logo'] = $info['business_logo'];
        $data['shop_name'] = $info['business_name'];

        $data['posttime'] = date('Y-m-d H:i:s');

        $data['static'] = 1;

        $static = db('yuyue')->insert($data);


        return $static;
    }
    //book页面数据加载
    public function bookjz()
    {
        $data['start'] = date('Y-m-d');

        $data['end'] = date('Y-m-d',strtotime('+10 day'));

return json_encode($data);
    }

    public function shop_address()
    {
        $info_id = input('get.info_id');

        $info = db('info')->find(input('get.info_id'));

        $data['lng'] = $info['business_lng'];
        $data['lat'] = $info['business_lat'];
        return json_encode($data);
    }
    //分享开始
     public function shengc()
    {
      $agent_id = input('get.agent_id');

      $shop_id = input('get.shop_id');

      $setting = db('setting')->find($agent_id);

      $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$setting['appid'].'&secret='.$setting['appsecret'];

      $shu = json_decode(httpGet($url));

      return json_encode($shu->access_token);

    }

    public function erweima()
    {

        $data = input('post.file');
       // $data = $this->uploadFile();
         $sData = file_get_contents("php://input");

        $a =file_put_contents("temp.png",$sData);
       //return json_encode($data);
    }

    public function shopyouhui()
    {


        //var_dump(time());die;
        $info_id = input('get.id');
        $where['lessen_date'] = ['>',time()];
        $where['business_id'] = input('get.id');

        $data = db::table('business_lessen')->where($where)->select();

        //var_dump($data);die;
        return json_encode($data);
    }

    //用户表操作
    public function inuser()
    {
        $data = input('get.');
        $data['create_time'] = time();
        $where['openid'] = $data['openid'];

        $users = db('users')->where($where)->find();

        if (!$users) {
           $data = db('users')->insert($data);
        }
        return json_encode($data);
    }


    public function deletewzfdd()
    {
        $data = input('get.orderid');


        db('order')->delete(input('get.orderid'));

        db('order_goods')->where('oid',input('get.orderid'))->delete();


    }

    public function qxyzf()
    {

        $where['is_comment'] = 1;
        $where['quxiao'] = 1;
        $where['id'] = input('get.orderid');

        db('order')->update($where);
        $order = db('order')->find(input('get.orderid'));
         $body['order_id'] = $order['order_num'];
        $body['cancel_reason_id'] = 4;
        //$body['cancel_reason_id'] = 4;

        $data['body'] = json_encode($body);
        $data['app_key'] = $this->app_key;
        $data['format'] = 'json';
        $data['v'] = '1.0';
        $data['source_id'] = '73753';
        $data['timestamp'] = time();

        $data['signature'] = $this->paixu($data);
        $data = $this->post($data,$this->qxorderurl);

        var_dump($data);
    }

      public function quxiaoyuanyin()
    {

        $data['app_key'] = $this->app_key;
        $data['body'] = '';
        $data['format'] = 'json';
        $data['v'] = '1.0';
        $data['source_id'] = '73753';
        $data['timestamp'] = time();

        $data['signature'] = $this->paixu($data);

        $data = $this->post($data,$this->qxyyurl);

        $data = $this->chuli($data);
        //var_dump($data);die;

        foreach ($data as $key => $value) {


           // var_dump($value->reason);
           // var_dump($value->id);

        }

    }




     public function paixu($data){
        //1.升序排序
        ksort($data);
        //2.字符串拼接
        $args = "";
        foreach ($data as $key => $value) {
            $args.=$key.$value;
        }
        $args = $this->app_secret.$args.$this->app_secret;

        //3.MD5签名,转为大写
       // $data['signature'] = strtoupper(md5($args));

        return strtoupper(md5($args));

        }

    public function shujv(){

            $data = $this->data;
            $data['timestamp'] = time();
           $data['signature'] = $this->paixu($data);

          $data = $this->post($data,$this->cityurl);

          $city = $this->city($data,'上海');

          return $city;

}


        public function post($data,$postUrl)
        {
            $data = json_encode($data);



        $curlPost = $data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        //var_dump($data);die;
        curl_close($ch);

        return $data;
        }

    public function city($data,$cityname){

        $data = $this->chuli($data);


      //var_dump($data);

          foreach ($data as $key => $value) {
                // var_dump($value->cityName);
                // var_dump($value->cityCode);die;

                // 判断达达配送地区是否有当前城市
            if ($value->cityName = $cityname) {


                return $value->cityCode;
            }
          }

  }

  public function chuli($data)
  {


        //处理返回结果
        //去除末尾
        $data =  substr_replace($data,"",-25);
        //去除开头
        $data = substr($data,29);
        //转化json
      $data = json_decode($data);

      //转化数组


      return (array)$data;
  }

  public function indexcity()
  {


        $arr = json_decode(rtrim(str_replace("renderReverse&&renderReverse(","",httpGet('http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='.input('get.lat').','.input('get.lng').'&output=json&pois=1&ak=A2vHtcav1E7fgqO1iiFWuPWt')), ')'),true);
        $data = $arr['result']['addressComponent']['street'].$arr['result']['addressComponent']['street_number'];

//var_dump($data);die;

        return json_encode($data);

        //return json_encode($arr['result']['addressComponent']['city']);






  }

  public function gettype()
  {

    $where['agent_id'] = input('get.agent_id');
    $where['static'] = 1;
    $data = db('shop_type')->where($where)->select();
    $a = array();
    foreach ($data as $key => $value) {
    $a[] = $value['shop_type_name'];
    }
//var_dump($a);die;
    return json_encode($a);


  }
  //根据两个经纬度查询距离
  public function jvli($lng1, $lat1, $lng2, $lat2) {


  	$lat1 = $_GET['lat1'];
  	$lat2 = $_GET['lat2'];
  	$lng1 = $_GET['lng1'];
  	$lng2 = $_GET['lng2'];
    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
} 
  //小程序端消息提醒
    public function wxtixing()
    {
        $data = db('order')->where('is_read',0)->where('is_comment',0)->find();



       db('order')->where('id', $data['id'])->update(['is_read' => '1']);
	return json_encode($data);
    }
  


}